<%@ page contentType="text/html; charset=utf-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<%@ taglib prefix="primus" tagdir="/WEB-INF/tags" %>
<%@ taglib prefix="pf" tagdir="/WEB-INF/tags/form" %>
<%@ taglib prefix="pbase" tagdir="/WEB-INF/tags/base" %>
<%@ taglib prefix="pbtn" tagdir="/WEB-INF/tags/btn" %>
<primus:page title="新增降价拍">
    <jsp:attribute name="script">
        <script type="application/javascript">
        </script>
    </jsp:attribute>
    <jsp:attribute name="css">
        <style type="text/css">

        </style>
    </jsp:attribute>
    <jsp:body>
        <%--<jsp:include page="../demo/cats/component/navigations.jsp"/>--%>
        <div class="breadcrumbs ace-save-state" id="breadcrumbs">
            <ul class="breadcrumb">
                <li>
                    <i class="ace-icon fa fa-home home-icon"></i>
                    <a href="welcome.do">
                        首页
                    </a>
                </li>
                <li>
                    降价拍
                </li>
                <li class="active">
                    新建降价拍
                </li>
            </ul>
            <a class="btn btn-xs btn-primary history-back">
                <i class="ace-icon fa fa-angle-left"></i>
                返回
            </a>
        </div>

        <div class="page-content">
            <div class="col-xs-12">
                <form id="special_offer_form" action="management/cutPriceSalePromotion/save.do"
                      method="post" class="form-horizontal" role="form">
                    <div class="form-group col-xs-12">
                        <div class="col-xs-10 col-sm-5">
                            <input type="hidden" name="id" value="${cutPriceSalePromotion.id}" id="id"/>
                        </div>
                    </div>
                    <pf:text _title="活动名称" _name="name"
                             _inputClass="required text col-xs-10 col-sm-5"
                             _value="${cutPriceSalePromotion.name}" _id="name"/>

                    <pbase:row layout="single">
                        <label class="col-sm-2 control-label no-padding-right" for="description">活动介绍</label>
                        <div class="col-xs-10 col-sm-5">
                            <textarea id="description" name="description" style="width: 100%"><c:out
                                    value="${cutPriceSalePromotion.description}"/></textarea>
                        </div>
                    </pbase:row>

                    <pbase:row layout="single">
                        <label class="col-sm-2 control-label no-padding-right"
                               for="channels">活动渠道</label>
                        <div class="col-sm-10 form-group">
                            <div class="col-xs-10 col-sm-5">
                                <primus:promotionChannelSelect fieldName="channels"
                                                               fieldId="channels"
                                                               selectedField="${cutPriceSalePromotion.channels}"
                                                               fmtCls="col-xs-10 col-sm-5"/>
                            </div>
                        </div>
                    </pbase:row>

                    <pbase:row layout="single">
                        <label class="col-sm-2 control-label no-padding-right"
                               for="scope">促销范围</label>
                        <div class="col-sm-10 form-group">
                            <primus:PromotionScopeSelectTag fieldId="scope"
                                                            valueType="${cutPriceSalePromotion.scope}"
                                                            fieldName="scope"
                                                            selectedField="${cutPriceSalePromotion.scope.name()}"
                                                            selectedFieldValue="${cutPriceSalePromotion.scopeIds}"/>
                        </div>
                    </pbase:row>

                    <pbase:row layout="single">
                        <label class="col-sm-2 control-label no-padding-right" for="memberLevel">会员等级</label>
                        <div class="col-sm-10 form-group">
                            <div class="col-xs-10 col-sm-5">
                                <primus:promotionMemberIdTag fieldId="memberLevel"
                                                             fieldName="effectMemberLevels"
                                                             selectedField="${cutPriceSalePromotion.effectMemberLevels}"
                                                             fmtCls="col-xs-10 col-sm-5"/>
                            </div>
                        </div>
                    </pbase:row>

                    <pf:date _title="开始时间" _id="startTime" _name="startTime"
                             _value="2017-11-16 10:47:43"/>

                    <pf:date _title="结束时间" _id="endTime" _name="endTime"
                             _value="${cutPriceSalePromotion.endTime}"/>

                    <primus:promotionCutPriceRule promotionId="${curPriceSalePromotion.id}" />

                    <pbase:row layout="single">
                        <label class="col-sm-2 control-label no-padding-right"
                               for="userOnceGainLimit">用户是否只能参与一次</label>
                        <div class="col-sm-10 form-group">
                            <div class="col-xs-10 col-sm-5">
                                <label>
                                    <input ${cutPriceSalePromotion.userOnceGainLimit}
                                            id="userOnceGainLimit" class="ace ace-switch ace-switch-6"
                                            type="checkbox"/>
                                    <span class="lbl"></span>
                                </label>
                            </div>
                        </div>
                    </pbase:row>

                    <pbase:row layout="single">
                        <label class="col-sm-2 control-label no-padding-right"
                               for="allowCoupon">是否允许使用优惠券</label>
                        <div class="col-sm-10 form-group">
                            <div class="col-xs-10 col-sm-5">
                                <label>
                                    <input ${cutPriceSalePromotion.allowCoupon ? 'checked' : ''}
                                            id="allowCoupon" class="ace ace-switch ace-switch-6"
                                            type="checkbox"/>
                                    <span class="lbl"></span>
                                </label>
                            </div>
                        </div>
                    </pbase:row>

                    <pbase:row layout="single">
                        <label class="col-sm-2 control-label no-padding-right"
                               for="status">是否启用</label>
                        <div class="col-sm-10 form-group">
                            <div class="col-xs-10 col-sm-5">
                                <label>
                                    <input ${cutPriceSalePromotion.commonStatus.name() == 'ENABLE' ? 'checked' : ''}
                                            id="status" class="ace ace-switch ace-switch-6"
                                            type="checkbox"/>
                                    <span class="lbl"></span>
                                </label>
                            </div>
                        </div>
                    </pbase:row>
                    <pbase:row layout="single">
                        <div>
                            <label>
                                <select id="categoryId">
                                    <option value="">全部分类</option>
                                    <option value="1">1</option>
                                </select>
                            </label>
                            <label>
                                <select id="brandId">
                                    <option value="">所有品牌</option>
                                    <option value="1">1</option>
                                </select>
                            </label>
                            <label>
                                <select id="product">
                                    <option value="">所有商品</option>
                                </select>
                            </label>
                            <label style="position: relative;z-index: 1111;">
                                <input class="typeahead scrollable" style="min-width: 0;"
                                       id="keyword" type="text" placeholder="搜索商品名称"/>
                            </label>
                        </div>
                        <table id="grid-table"></table>

                        <div id="grid-pager"></div>

                    </pbase:row>
                    <div class="clearfix form-actions">
                        <div class="col-md-offset-3 col-md-9">
                            <button class="btn btn-info" type="button" id="special_offer_create_btn"
                                    style="margin-right: 20px;" onclick="do_submit();"><i
                                    class="ace-icon fa fa-check bigger-110"></i>提交
                            </button>
                            <pbtn:reset/>
                        </div>
                    </div>
                </form>
            </div>
        </div>
        <script>

            $(function () {
                var productData;
                $("#categoryId").change(function () {
                    $.ajax({
                        url: "management/cutPriceSalePromotion/products/search.do", data: {
                            categoryId: $("#categoryId").val(), brandId: $("#brandId").val()
                        }, dataType: "json", type: "post", success: function (d) {
                            console.log(d);
                            productData = d;
                            $("#product option[value!='']").remove();
                            $(d).each(function (k, v) {
                                $("#product")
                                    .append('<option value="'
                                        + v.productId
                                        + '">'
                                        + v.productName
                                        + '</option>')
                            })
                        }
                    })
                })
                $("#brandId").change(function () {
                    $.ajax({
                        url: "management/cutPriceSalePromotion/products/search.do", data: {
                            categoryId: $("#categoryId").val(), brandId: $("#brandId").val()
                        }, dataType: "json", type: "post", success: function (d) {
                            console.log(d);
                            productData = d;
                            $("#product option[value!='']").remove();
                            $(d).each(function (k, v) {
                                $("#product")
                                    .append('<option value="'
                                        + v.productName
                                        + '">'
                                        + v.productName
                                        + '</option>')
                            })
                        }
                    })
                })
                $("#product").change(function () {
                    $(productData).each(function (k, v) {
                        if (v.productName === $("#product").val()) {
                            $("#grid-table").jqGrid('addRowData', v.productId, v, "first");
                        }
                    })
                })

                var productAll;
                //typeahead.js
                //example taken from plugin's page at: https://twitter.github.io/typeahead.js/examples/
                var substringMatcher = function (strs) {
                    return function findMatches(q, cb) {
                        var matches, substringRegex;
                        // an array that will be populated with substring matches
                        matches = [];
                        // regex used to determine if a string contains the substring `q`
                        substrRegex = new RegExp(q, 'i');
                        // iterate through the pool of strings and for any string that
                        // contains the substring `q`, add it to the `matches` array
                        $.each(strs, function (i, str) {
                            if (substrRegex.test(str)) {
                                // the typeahead jQuery plugin expects suggestions to a
                                // JavaScript object, refer to typeahead docs for more info
                                matches.push({value: str});
                            }
                        });
                        cb(matches);
                    }
                }
                $.ajax({
                    url: "management/cutPriceSalePromotion/products/search.do",
                    data: {},
                    dataType: "json",
                    type: "post",
                    success: function (d) {
                        console.log(d);
                        productAll = d;
                        var source = [];
                        $(d).each(function (k, v) {
                            source.push(v.productName)
                        });
                        console.log(source);
                        $('#keyword').typeahead({
                            hint: true, highlight: true, minLength: 1
                        }, {
                            name: 'states',
                            displayKey: 'value',
                            source: substringMatcher(source),
                            limit: 1000000
                        });
                    }
                })
                $("#keyword").change(function () {
                    $(productAll).each(function (k, v) {
                        if (v.productName === $("#keyword").val()) {
                            $("#grid-table").jqGrid('addRowData', v.productId, v, "first");
                        }
                    })
                    //console.log($("#keyword").val())
                })

            })

            $(function () {
                var grid_selector = "#grid-table";
                var pager_selector = "#grid-pager";
                var lastsel;
                $(grid_selector).jqGrid({
                    //direction: "rtl",

                    url: "management/cutPriceSalePromotion/products.do",
                    datatype: "json",
                    height: 250,
                    colNames: ['ID', '商品分类', '商品品牌', '商品编码', '商品名称'],
                    colModel: [{
                        name: 'productId',
                        index: 'productId',
                        width: 60,
                        sorttype: "int"
                    }, {name: 'categoryName', index: 'categoryName', width: 90}, {
                        name: 'brandName',
                        index: 'brandName',
                        width: 150
                    }, {name: 'productCode', index: 'productCode', width: 70}, {
                        name: 'productName',
                        index: 'productName',
                        width: 90
                    }],

                    viewrecords: true,
                    rowNum: 10,
                    rowList: [10, 20, 30],
                    pager: pager_selector,
                    altRows: true, //toppager: true,

                    multiselect: true, //multikey: "ctrlKey",
                    //multiboxonly: true,

                    loadComplete: function () {
                        var table = this;
                        setTimeout(function () {
                            styleCheckbox(table);
                            updateActionIcons(table);
                            updatePagerIcons(table);
                            enableTooltips(table);
                        }, 0);
                    }, /*onSelectRow : function(id) {
                        if (id && id !== lastsel) {
                            $(grid_selector).jqGrid('restoreRow', lastsel);
                            $(grid_selector).jqGrid('editRow', id, true);
                            lastsel = id;
                        }
                    },*/
                    editurl: "",
                    caption: "活动商品"
                })

                var parent_column = $(grid_selector).closest('[class*="col-"]');
                //resize to fit page size
                $(window).on('resize.jqGrid', function () {
                    $(grid_selector).jqGrid('setGridWidth', parent_column.width());
                })
                //resize on sidebar collapse/expand
                $(document).on('settings.ace.jqGrid', function (ev, event_name, collapsed) {
                    if (event_name
                        === 'sidebar_collapsed'
                        || event_name
                        === 'main_container_fixed') {
                        //setTimeout is for webkit only to give time for DOM changes and then redraw!!!
                        setTimeout(function () {
                            $(grid_selector).jqGrid('setGridWidth', parent_column.width());
                        }, 20);
                    }
                })
                $(window).triggerHandler('resize.jqGrid');//trigger window resize to make the grid get the correct size

                //switch element when editing inline
                function aceSwitch(cellvalue, options, cell) {
                    setTimeout(function () {
                        $(cell).find('input[type=checkbox]')
                            .addClass('ace ace-switch ace-switch-5')
                            .after('<span class="lbl"></span>');
                    }, 0);
                }

                //enable datepicker
                function pickDate(cellvalue, options, cell) {
                    setTimeout(function () {
                        $(cell).find('input[type=text]')
                            .datepicker({format: 'yyyy-mm-dd', autoclose: true});
                    }, 0);
                }

                $(grid_selector)
                    .jqGrid('navGrid', pager_selector, {
                        edit: false,
                        add: false,
                        del: false,
                        search: false,
                        refresh: true,
                        refreshicon: 'ace-icon fa fa-refresh green'
                    })
                    .jqGrid('navButtonAdd', pager_selector, {
                        caption: "",
                        buttonicon: "ace-icon fa fa-plus-circle purple",
                        onClickButton: function () {
                            $(grid_selector).jqGrid("addRow");
                        },
                        position: "last",
                        title: "添加",
                        cursor: "pointer",
                        id: ""
                    })
                    .jqGrid('navButtonAdd', pager_selector, {
                        caption: "",
                        buttonicon: "ace-icon fa fa-pencil blue",
                        onClickButton: function () {
                            $($(grid_selector).jqGrid('getGridParam', 'selarrrow'))
                                .each(function (k, v) {
                                    $(grid_selector).jqGrid("editRow", v);
                                })
                        },
                        position: "last",
                        title: "编辑",
                        cursor: "pointer",
                        id: ""
                    })
                    .jqGrid('navButtonAdd', pager_selector, {
                        caption: "",
                        buttonicon: "ace-icon fa fa-check orange",
                        onClickButton: function () {
                            $($(grid_selector).jqGrid('getGridParam', 'selarrrow'))
                                .each(function (k, v) {
                                    $(grid_selector).jqGrid("saveRow", v);
                                })
                            $($(grid_selector).jqGrid('getDataIDs')).each(function (k, v) {
                                $(grid_selector).jqGrid("restoreRow", v);
                            })
                        },
                        position: "last",
                        title: "完成",
                        cursor: "pointer",
                        id: ""
                    })
                    .jqGrid('navButtonAdd', pager_selector, {
                        caption: "",
                        buttonicon: "ace-icon fa fa-trash-o red",
                        onClickButton: function () {
                            $($(grid_selector).jqGrid('getGridParam', 'selarrrow'))
                                .each(function (k, v) {
                                    $(grid_selector).jqGrid("delRowData", v);
                                })
                        },
                        position: "last",
                        title: "删除",
                        cursor: "pointer",
                        id: ""
                    });
                /*$(grid_selector).jqGrid('navGrid', pager_selector, {
                    edit: true,
                    editicon : 'ace-icon fa fa-pencil blue',
                    add: true,
                    addicon : 'ace-icon fa fa-plus-circle purple',
                    del: true,
                    delicon : 'ace-icon fa fa-trash-o red',
                    refresh: true,
                    refreshicon : 'ace-icon fa fa-refresh green',
                    search: false
                });*/
                //$(grid_selector).jqGrid('inlineNav', pager_selector);

                //it causes some flicker when reloading or navigating grid
                //it may be possible to have some custom formatter to do this as the grid is being created to prevent this
                //or go back to default browser checkbox styles for the grid
                function styleCheckbox(table) {
                    /**
                     $(table).find('input:checkbox').addClass('ace')
                     .wrap('<label />')
                     .after('<span class="lbl align-top" />')


                     $('.ui-jqgrid-labels th[id*="_cb"]:first-child')
                     .find('input.cbox[type=checkbox]').addClass('ace')
                     .wrap('<label />').after('<span class="lbl align-top" />');
                     */
                }

                //unlike navButtons icons, action icons in rows seem to be hard-coded
                //you can change them like this in here if you want
                function updateActionIcons(table) {
                    /**
                     var replacement =
                     {
                         'ui-ace-icon fa fa-pencil' : 'ace-icon fa fa-pencil blue',
                         'ui-ace-icon fa fa-trash-o' : 'ace-icon fa fa-trash-o red',
                         'ui-icon-disk' : 'ace-icon fa fa-check green',
                         'ui-icon-cancel' : 'ace-icon fa fa-times red'
                     };
                     $(table).find('.ui-pg-div span.ui-icon').each(function(){
						var icon = $(this);
						var $class = $.trim(icon.attr('class').replace('ui-icon', ''));
						if($class in replacement) icon.attr('class', 'ui-icon '+replacement[$class]);
					})
                     */
                    /*$(table).closest(".ui-jqgrid").find(".ui-jqgrid-pager .ui-icon-search").removeClass("ui-icon-search").addClass("fa fa-search");
                    $(table).closest(".ui-jqgrid").find(".ui-jqgrid-pager .ui-icon-refresh").removeClass("ui-icon-refresh").addClass("fa fa-refresh");
                    $(table).closest(".ui-jqgrid").find(".ui-jqgrid-pager .ui-icon-plus").removeClass("ui-icon-plus").addClass("fa fa-plus-circle");*/
                }

                //replace icons with FontAwesome icons like above
                function updatePagerIcons(table) {
                    var replacement = {
                        'ui-icon-seek-first': 'ace-icon fa fa-angle-double-left bigger-140',
                        'ui-icon-seek-prev': 'ace-icon fa fa-angle-left bigger-140',
                        'ui-icon-seek-next': 'ace-icon fa fa-angle-right bigger-140',
                        'ui-icon-seek-end': 'ace-icon fa fa-angle-double-right bigger-140'
                    };
                    $('.ui-pg-table:not(.navtable) > tbody > tr > .ui-pg-button > .ui-icon')
                        .each(function () {
                            var icon = $(this);
                            var $class = $.trim(icon.attr('class').replace('ui-icon', ''));

                            if ($class in replacement) icon.attr('class', 'ui-icon '
                                + replacement[$class]);
                        })
                }

                function enableTooltips(table) {
                    $('.navtable .ui-pg-button').tooltip({container: 'body'});
                    $(table).find('.ui-pg-div').tooltip({container: 'body'});
                }
            });

            function do_submit() {
                var effect_product_ids = [];
                var promotion_products = $("#grid-table").jqGrid('getRowData');
                for (var i in promotion_products) {
                    effect_product_ids.push(promotion_products[i].productId);
                }

                var rates = [];
                $('#_rate_table > tbody').find('tr').each(function () {
                    var $this = $(this);
                    rates.push({
                        rateCondition: $this.children('.condition').find('input').val(),
                        discountRate: $this.children('.discountRate').find('input').val()
                    });
                });

                var form_data = {
                    id: $('#id').val(),
                    name: $('#name').val(),
                    description: $('#description').val(),
                    channels: $('#channels').val(),
                    scope: $('#scope').val(),
                    scopeIds: $('#scope-value').val(),
                    effectMemberLevels: $('#memberLevel').val(),
                    startTime: $('#startTime').val(),
                    endTime: $('#endTime').val(),
                    status: $('#status').val() === "on" ? "ENABLE" : "DISABLE",
                    limitProductIds: effect_product_ids,
                    allowCoupon: $('#allowCoupon').val === "on",
                    limitType: $('#limitType').val(),
                    discountRates: rates,
                    isStairCut: rates.length > 1,
                    stairCount: rates.length
                };
                $.ajax({
                    cache: true,
                    async: false,
                    url: 'management/cutPriceSalePromotion/save.do',
                    type: 'post',
                    dataType: 'json',
                    data: {data: JSON.stringify(form_data)}
                }).success(function (result) {
                    if (result) {
                        window.location.href = "management/cutPriceSalePromotion/list.do"
                    }
                });
            }
        </script>
    </jsp:body>
</primus:page>
